﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using log4net;

namespace ModelQuality.Metrics.Utils
{
    static class AppUtils
    {
        private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        
        /// <summary>
        /// http://www.dotnetperls.com/percentage
        /// </summary>
        /// <param name="count"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public static int GetPercent(int count, int total)
        {
            int ret;
            if (total > 0)
            {
                double percent = (double)(count * 100) / total;
                ret = Convert.ToInt32(Math.Floor(percent));
            }
            else
            {
                ret = 0;
            }

            return ret;
        }

        /// <summary>
        /// http://stackoverflow.com/questions/2714639/weighted-average-with-linq
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="records"></param>
        /// <param name="value"></param>
        /// <param name="weight"></param>
        /// <returns></returns>
        public static double WeightedAverage<T>(this IEnumerable<T> records, Func<T, double> value, Func<T, double> weight)
        {
            double ret;
            double weightSum = records.Sum(weight);
            if (weightSum > 0)
            {
                double weightedValueSum = records.Sum(record => value(record) * weight(record));
                ret = weightedValueSum / weightSum;
                log.DebugFormat("Weighted sum: {0}, weight sum: {1}, calculated weigthed average: {2}", weightedValueSum, weightSum, ret);
            }
            else
            {
                ret = 0;
                log.Warn("Unable to calculate weighted average as sum of weigths is 0");
            }

            
            return ret;
        }
    }
}
